package cn.ug.analyse.service.impl;

import cn.ug.analyse.bean.ChannelBean;
import cn.ug.analyse.bean.ChannelStaffBean;
import cn.ug.analyse.bean.ChannelUserBean;
import cn.ug.analyse.bean.RewardPlanBean;
import cn.ug.analyse.bean.response.BaseBean;
import cn.ug.analyse.bean.response.BaseCountExtendBean;
import cn.ug.analyse.bean.response.BaseOperationBean;
import cn.ug.analyse.bean.response.BuyGoldBean;
import cn.ug.analyse.mapper.ChannelMapper;
import cn.ug.analyse.mapper.ChannelStaffMapper;
import cn.ug.analyse.mapper.MemberAnalyseMapper;
import cn.ug.analyse.mapper.MemberOperationMapper;
import cn.ug.analyse.mapper.entity.*;
import cn.ug.analyse.service.ChannelService;
import cn.ug.analyse.web.submit.ChannelSubmit;
import cn.ug.bean.base.DataOtherTable;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.pay.bean.MemberGoldBean;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.*;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 渠道管理
 *
 * @author zhaohg
 * @date 2018/08/06.
 */
@Service
public class ChannelServiceImpl extends BaseServiceImpl implements ChannelService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private ChannelMapper channelMapper;
    @Resource
    private ChannelStaffMapper channelStaffMapper;
    @Resource
    private DozerBeanMapper dozerBeanMapper;
    @Resource
    private MemberAnalyseMapper memberAnalyseMapper;
    @Autowired
    private MemberOperationMapper memberOperationMapper;
    /**
     * 商户默认密码
     */
    private static final String STAFF_DEFAULT_PASSWORD = "UG945723";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SerializeObject insert(ChannelSubmit submit) {
        submit.checkAddChannelParams();

        ChannelEntity entity = dozerBeanMapper.map(submit, ChannelEntity.class);
        //获取渠道最大编号
        String channelNumber = String.valueOf(channelMapper.maxChannelNumber());
        channelNumber = ChannelNumberUtil.getInstance().nextChannelNumber(channelNumber);
        entity.setNumber(channelNumber);
        entity.setPassword(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD));
        int success = channelMapper.insert(entity);
        if (success > 0) {
            ChannelStaffEntity channelStaffEntity = channelStaffMapper.getStaffByMobile(submit.getMobile());
            if (channelStaffEntity != null) {
                Ensure.that(true).isTrue("210000024");
            }
            ChannelStaffEntity staff = dozerBeanMapper.map(submit, ChannelStaffEntity.class);
            //获取成员最大编号
            String staffNumber = String.valueOf(channelStaffMapper.maxStaffNumber(entity.getId()));
            staffNumber = ChannelNumberUtil.getInstance().nextStaffNumber(staffNumber, channelNumber);
            staff.setNumber(staffNumber);
            staff.setChannelId(entity.getId());
            staff.setInviteCode(UF.getRandomUUID()); // TODO 邀请码
            staff.setPassword(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD));
            channelStaffMapper.insert(staff);

            entity.setRelationId(staff.getId());
            channelMapper.update(entity);
            channelMapper.updateStaffCount(entity.getId());
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject updateRewardPlan(ChannelSubmit submit) {
        submit.checkPlanParams();

        ChannelEntity entity = dozerBeanMapper.map(submit, ChannelEntity.class);
        List<RewardPlanBean> planList = submit.getPlanList();
        if (CollectionUtils.isNotEmpty(planList)) {
            String planJsonStr = JSONObject.toJSONString(planList);
            entity.setPlanStep(planJsonStr);
        }

        int success = channelMapper.updateRewardPlan(entity);
        if (success > 0) {
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject updateInvitation(ChannelSubmit submit) {
        submit.checkInvitationParams();

        ChannelEntity entity = dozerBeanMapper.map(submit, ChannelEntity.class);
        int success = channelMapper.updateInvitation(entity);
        if (success > 0) {
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject updateChannelStatus(ChannelSubmit submit) {
        submit.checkStatusParams();
        ChannelEntity channel = channelMapper.findById(submit.getId());
        if (channel == null || channel.getOneInviteReward().compareTo(BigDecimal.ZERO) < 0
                || channel.getPlanStep() == null) {
            return new SerializeObjectError("210000025");
        }
        ChannelEntity entity = dozerBeanMapper.map(submit, ChannelEntity.class);
        int success = channelMapper.updateChannelStatus(entity);
        if (success > 0) {
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject findById(Long id) {
        ChannelEntity entity = channelMapper.findById(id);
        if (entity != null) {
            ChannelBean bean = dozerBeanMapper.map(entity, ChannelBean.class);
            String jsonStr = entity.getPlanStep();
            if (jsonStr != null) {
                List<RewardPlanBean> planList = JSONObject.parseArray(jsonStr, RewardPlanBean.class);
                bean.setPlanList(planList);
            }
            return new SerializeObject<>(ResultType.NORMAL, "00000001", bean);
        }

        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject findList(ChannelSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setParams(querySubmit);

        int count = channelMapper.count(querySubmit);
        Page page = new Page(submit.getPageNum(), submit.getPageSize(), count);
        List<ChannelBean> list = new ArrayList<>(count);
        if (count > 0) {
            List<ChannelEntity> channelList = channelMapper.findList(querySubmit);

//            Map<Long, ChannelEntity> channelMap = channelList.stream().collect(Collectors.toMap(ChannelEntity::getRelationId, ChannelEntity -> ChannelEntity));

            List<Long> ids = channelList.stream().map(ChannelEntity::getRelationId).collect(Collectors.toList());

            List<ChannelStaffEntity> staffList = channelStaffMapper.findByIds(ids);
            Map<Long, ChannelStaffEntity> staffMap = staffList.stream().collect(Collectors.toMap(ChannelStaffEntity::getId, ChannelStaffEntity -> ChannelStaffEntity));

//            Iterator<Map.Entry<Long, ChannelEntity>> iterator = channelMap.entrySet().iterator();
            Iterator<ChannelEntity> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                ChannelEntity entity = iterator.next();

//                Map.Entry<Long, ChannelEntity> entry = iterator.next();

//                ChannelEntity entryValue = entry.getValue();
                ChannelBean bean = dozerBeanMapper.map(entity, ChannelBean.class);

                String jsonStr = entity.getPlanStep();
                if (jsonStr != null) {
                    List<RewardPlanBean> planList = JSONObject.parseArray(jsonStr, RewardPlanBean.class);
                    bean.setPlanList(planList);
                }
                ChannelStaffEntity staff = staffMap.get(entity.getRelationId());
                if (staff != null) {
                    bean.setStaff(dozerBeanMapper.map(staff, ChannelStaffBean.class));
                }
                list.add(bean);
            }
        }

        return new SerializeObject<>(ResultType.NORMAL, "00000001", new DataTable<>(page, list));
    }

    @Override
    public SerializeObject<ChannelUserBean> verifyLogin(String channelName, String passWord, Integer type) {
        //渠道商验证
        if (type == 0) {
            ChannelEntity entity = channelMapper.findByName(channelName);
            if (entity == null)
                return new SerializeObjectError("210000029");

            //密码正确
            if (DigestUtils.md5Hex(passWord).equals(entity.getPassword())) {
                ChannelUserBean channelUserBean = new ChannelUserBean();
                channelUserBean.setId(entity.getId());
                channelUserBean.setChannelId(entity.getId());
                channelUserBean.setChannelNumber(entity.getNumber());
                channelUserBean.setName(entity.getName());
                channelUserBean.setType(type);
                channelUserBean.setAddTime(DateUtils.dateToStr(entity.getAddTime(), DateUtils.patter));
                channelUserBean.setStaffId(entity.getRelationId());
                String newPassword = DigestUtils.md5Hex(passWord);
                channelUserBean.setPassWrodStatus(newPassword.equals(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD)) ? 0 : 1);
                return new SerializeObject<>(ResultType.NORMAL, "00000001", channelUserBean);
            }
        } else {
            //渠道成员验证
            ChannelStaffEntity channelStaffEntity = channelStaffMapper.getStaffByMobile(channelName);
            if (channelStaffEntity == null)
                return new SerializeObjectError("210000028");

            if (DigestUtils.md5Hex(passWord).equals(channelStaffEntity.getPassword())) {
                ChannelUserBean channelUserBean = new ChannelUserBean();
                channelUserBean.setId(channelStaffEntity.getId());
                channelUserBean.setChannelId(channelStaffEntity.getChannelId());
                channelUserBean.setChannelNumber(channelStaffEntity.getNumber());
                channelUserBean.setName(channelStaffEntity.getRealName());
                channelUserBean.setType(type);
                channelUserBean.setMobile(channelName);
                channelUserBean.setAddTime(DateUtils.dateToStr(channelStaffEntity.getAddTime(), DateUtils.patter));
                String newPassword = DigestUtils.md5Hex(passWord);
                channelUserBean.setPassWrodStatus(newPassword.equals(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD)) ? 0 : 1);
                channelUserBean.setInviteCode(channelStaffEntity.getInviteCode());
                return new SerializeObject<>(ResultType.NORMAL, "00000001", channelUserBean);
            }
        }
        return new SerializeObjectError("210000026");
    }

    /**
     * 获取启用的、并在有效时间内的渠道
     *
     * @return
     */
    @Override
    public List<ChannelBean> findListByDate(Date date) {
        QuerySubmit querySubmit = new QuerySubmit();
        querySubmit.put("currentDate", date);//当天日期
        querySubmit.setLimit(null, null);

        int count = channelMapper.count(querySubmit);
        List<ChannelBean> list = new ArrayList<>(count);
        if (count > 0) {
            List<ChannelEntity> channelList = channelMapper.findList(querySubmit);
            Iterator<ChannelEntity> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                ChannelEntity entity = iterator.next();
                ChannelBean bean = dozerBeanMapper.map(entity, ChannelBean.class);
                String jsonStr = entity.getPlanStep();
                if (jsonStr != null) {
                    List<RewardPlanBean> planList = JSONObject.parseArray(jsonStr, RewardPlanBean.class);
                    bean.setPlanList(planList);
                }
                list.add(bean);
            }
        }

        return list;
    }

    @Override
    public List<ChannelBean> export(ChannelSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        querySubmit.put("name", submit.getName());
        querySubmit.setLimit(null, null);

        int count = channelMapper.count(querySubmit);
        List<ChannelBean> list = new ArrayList<>(count);
        if (count > 0) {
            List<ChannelEntity> channelList = channelMapper.findList(querySubmit);
            Iterator<ChannelEntity> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                ChannelBean bean = dozerBeanMapper.map(iterator.next(), ChannelBean.class);
                list.add(bean);
            }
        }
        return list;
    }

    @Override
    public SerializeObject resetPassword(Long id) {
        String password = DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD);
        channelMapper.resetPassword(id, password);
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject updatePassWord(Long id, String newPassWord, Integer type, String mobile) {
        String password = DigestUtils.md5Hex(newPassWord);
        if (password.equalsIgnoreCase(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD)))
            return new SerializeObjectError("210000027");

        if (type == 0) {
            channelMapper.resetPassword(id, password);
        } else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(mobile)) {
                ChannelStaffEntity channelStaffEntity = channelStaffMapper.getStaffByMobile(mobile);
                if (channelStaffEntity == null)
                    return new SerializeObjectError("210000028");

                channelStaffMapper.resetPassword(channelStaffEntity.getId(), password);
            } else {
                channelStaffMapper.resetPassword(id, password);
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject<ChannelStaffBean> findChannelStaffByMobile(String mobile) {
        ChannelStaffEntity channelStaffEntity = channelStaffMapper.getStaffByMobile(mobile);
        if (channelStaffEntity == null)
            return new SerializeObjectError("210000028");

        ChannelStaffBean channelStaffBean = dozerBeanMapper.map(channelStaffEntity, ChannelStaffBean.class);
        return new SerializeObject(ResultType.NORMAL, "00000001", channelStaffBean);
    }

    //    @Override
//    public int addChannelReward(Long id, BigDecimal amount) {
//        return channelMapper.addChannelReward(id, amount);
//    }

//    @Override
//    public int settleChannelReward(Long id, BigDecimal amount) {
//        return channelMapper.settleChannelReward(id, amount);
//    }


    @Override
    public DataOtherTable statistics(String channels, int pageNum, int pageSize) {
        com.github.pagehelper.Page<MemberGoldBean> resultPage = PageHelper.startPage(pageNum, pageSize);
        List<ChannelStatisticsBean> channelStatisticsBeanList = channelMapper.findStatisticsList(channels);
        //查询活动渠道信息
        String channelIds = channelMapper.queryActivityChannelId();
        if (!org.springframework.util.CollectionUtils.isEmpty(channelStatisticsBeanList)) {
            for (ChannelStatisticsBean channelBean : channelStatisticsBeanList) {
                //根据渠道id获取当前渠道总uv 不分日
                List<UvEntity> uvEntityList = channelMapper.queryUvBychannelId(channelBean.getChannelId(), 1);
                if (!org.springframework.util.CollectionUtils.isEmpty(uvEntityList)) {
                    channelBean.setUv(uvEntityList.get(0).getUv());
                }

                if (StringUtils.isNotBlank(channelIds) && channelIds.contains(channelBean.getChannelId())) {
                    channelBean.setNewJoinUserNum(channelMapper.queryJoinNumByChannelId(channelBean.getChannelId()));
                }

                List<BaseOperationBean> baseOperationBeanList = channelMapper.statistics(channelBean.getChannelId(), 1);
                Map<Integer, List<BaseOperationBean>> listMap = baseOperationBeanList.stream().collect(Collectors.groupingBy(b -> b.getType()));
                for (int i = 1; i <= 8; i++) {
                    BaseOperationBean operationBean = listMap.get(i).get(0);
                    if (operationBean != null) {
                        if (i == 1) {
                            channelBean.setRegisterNum(operationBean.getRegisterNum());
                            channelBean.setBdCardNum(operationBean.getBdCardNum());
                            continue;
                        }
                        if (i == 2) {
                            channelBean.setSoldGoldNum(operationBean.getSoldGoldNum());
                            channelBean.setSoldGoldGram(operationBean.getSoldGoldGram());
                            continue;
                        }

                        if (i == 3) {
                            channelBean.setBalanceAmount(operationBean.getBalanceAmount());
                            continue;
                        }

                        if (i == 4) {
                            channelBean.setWithdrawAmount(operationBean.getWithdrawAmount());
                            continue;
                        }

                        if (i == 5) {
                            channelBean.setCouponNum(operationBean.getCouponNum());
                            continue;
                        }

                        if (i == 6) {
                            channelBean.setFirstBuyNum(operationBean.getFirstBuyNum());
                            continue;
                        }

                        if (i == 7) {
                            channelBean.setAgainBuyNum(operationBean.getAgainBuyNum());
                            continue;
                        }

                        if (i == 8) {
                            channelBean.setBuyGoldNum(operationBean.getBuyGoldNum());
                            channelBean.setBuyGoldGram(operationBean.getBuyGoldGram());
                            channelBean.setBuyGoldAmount(operationBean.getBuyGoldAmount());
                            channelBean.setAverageBuyGoldAmount(operationBean.getBuyGoldAmount().compareTo(new BigDecimal(0)) == 0 ? BigDecimal.ZERO : operationBean.getBuyGoldAmount().divide(new BigDecimal(operationBean.getBuyGoldNum()), 2, BigDecimal.ROUND_HALF_UP));
                            continue;
                        }
                    }
                }
            }
        }
        Map resultMap = new HashMap();
        if (StringUtils.isNotBlank(channels)) {
            List<Map> mapList = memberOperationMapper.queryStockList(new HashMap());
            Integer totalBuyGoldGram = channelStatisticsBeanList.stream().collect(Collectors.summingInt(BaseOperationBean::getBuyGoldGram));
            Integer totalBuyGoldNum = channelStatisticsBeanList.stream().collect(Collectors.summingInt(BaseOperationBean::getBuyGoldNum));
            BigDecimal totalTraderAmount = channelStatisticsBeanList.stream().map(BaseOperationBean::getBuyGoldAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            //注册总数（人）
            resultMap.put("totalRegisterNum", channelStatisticsBeanList.stream().collect(Collectors.summingInt(BaseOperationBean::getRegisterNum)));
            //绑卡总数（人）
            resultMap.put("totalBdCardNum", channelStatisticsBeanList.stream().collect(Collectors.summingInt(BaseOperationBean::getBdCardNum)));
            //交易总数（人）  = 每日买金人数总和
            resultMap.put("totalBuyGoldNum", totalBuyGoldNum);
            //交易总量（g）  = 每日买金克重总和
            resultMap.put("totalBuyGoldGram", totalBuyGoldGram);
            //交易存量（g）
            resultMap.put("totalTraderGram", mapList.get(0).get("totalTraderGram"));
            //黄金总存量（g）
            resultMap.put("totalGoldGram", mapList.get(1).get("totalGoldGram"));
            //平台交易总金额（元） = 每日买金金额总和
            resultMap.put("totalTraderAmount", totalTraderAmount);
            //用户账户总余额（元）
            resultMap.put("totalBalanceAmount", channelStatisticsBeanList.stream().map(BaseOperationBean::getBalanceAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
            //人均购买金额（元）= 交易总量/交易总数
            resultMap.put("totalAverageBuyAmount", totalTraderAmount.compareTo(new BigDecimal(0)) == 0 ? 0 : totalTraderAmount.divide(new BigDecimal(totalBuyGoldNum), 2, BigDecimal.ROUND_HALF_UP));
        } else {
            List<Map> mapList = memberOperationMapper.queryStockList(new HashMap());
            List<Map> registerAndBdCardAndBalanceAmountList = memberOperationMapper.queryAllChannelRegisterAndBdCardAndBalanceAmount();
            BigDecimal totalTraderAmount = new BigDecimal(mapList.get(2).get("totalTraderAmount").toString());
            Integer totalBuyGoldNum = Integer.valueOf(mapList.get(2).get("totalBuyGoldNum").toString());
            //注册总数（人）
            resultMap.put("totalRegisterNum", registerAndBdCardAndBalanceAmountList.get(0).get("totalRegisterNum"));
            //绑卡总数（人）
            resultMap.put("totalBdCardNum", registerAndBdCardAndBalanceAmountList.get(1).get("totalBdCardNum"));
            //交易总数（人）  = 每日买金人数总和
            resultMap.put("totalBuyGoldNum", totalBuyGoldNum);
            //交易总量（g）  = 每日买金克重总和
            resultMap.put("totalBuyGoldGram", mapList.get(2).get("totalBuyGoldGram"));
            //交易存量（g）
            resultMap.put("totalTraderGram", mapList.get(0).get("totalTraderGram"));
            //黄金总存量（g）
            resultMap.put("totalGoldGram", mapList.get(1).get("totalGoldGram"));
            //平台交易总金额（元） = 每日买金金额总和
            resultMap.put("totalTraderAmount", totalTraderAmount);
            //用户账户总余额（元）
            resultMap.put("totalBalanceAmount", registerAndBdCardAndBalanceAmountList.get(2).get("totalBalanceAmount"));
            //人均购买金额（元）= 交易总量/交易总数
            resultMap.put("totalAverageBuyAmount", totalTraderAmount.compareTo(new BigDecimal(0)) == 0 ? 0 : totalTraderAmount.divide(new BigDecimal(totalBuyGoldNum), 2, BigDecimal.ROUND_HALF_UP));
        }
        return new DataOtherTable<>(resultPage.getPageNum(), resultPage.getPageSize(), resultPage.getTotal(), channelStatisticsBeanList, resultMap);
    }


    @Override
    public DataOtherTable findDetail(String channelStartTime, String channelEndTime, String channelId, int pageNum, int pageSize) {
        String channelIds = channelMapper.queryActivityChannelId();
        List<BaseBean> channelList = null;
        if (StringUtils.isNotBlank(channelIds) && channelIds.contains(channelId)) {
            channelList = channelMapper.queryEveryDayJoinNumByChannelId(channelId);
        }
        List<ChannelStatisticsBean> resultList = new ArrayList<>();
        Boolean flag = true;
        if (StringUtils.isBlank(channelStartTime)) {
            flag = false;
            channelStartTime = LocalDate.now().plusDays(-365).toString();
        }

        if (StringUtils.isBlank(channelEndTime))
            channelEndTime = LocalDate.now().toString();


        //参数必须传递--起始时间、结束时间
        Ensure.that(channelStartTime).isNull("21000001");
        Ensure.that(channelEndTime).isNull("21000002");
        //查询每天买金的人数
        List<BaseCountExtendBean> baseCountBeanList = memberOperationMapper.queryEverydayList(channelId);
        //每日首投人数  1.按照时间进行分组
        Map<Integer, List<BaseCountExtendBean>> traderNumMap = baseCountBeanList.stream().collect(Collectors.groupingBy(b -> b.getTraderNum()));
        //每日首投人数  1.按照时间进行分组
        Map<String, List<BaseCountExtendBean>> everydayMap = baseCountBeanList.stream().collect(Collectors.groupingBy(b -> b.getDay()));
        List<BuyGoldBean> buyGoldList = new ArrayList();
        for (String key : everydayMap.keySet()) {
            BuyGoldBean buyGoldBean = new BuyGoldBean();
            buyGoldBean.setDay(key);
            List<BaseCountExtendBean> beanList = everydayMap.get(key);
            //当天首次买金
            Long firstNum = beanList.stream().filter(o -> o.getTraderNum() == 1).count();
            int agianNum = beanList.size() - firstNum.intValue();
            //当天买金总金额/交易总量
            BigDecimal buyGoldAmount = beanList.stream().map(BaseCountExtendBean::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            Integer buyGoldGram = beanList.stream().collect(Collectors.summingInt(BaseCountExtendBean::getTotalGram));
            buyGoldBean.setFirstBuyNum(firstNum.intValue());
            buyGoldBean.setAgainBuyNum(agianNum);
            buyGoldBean.setBuyGoldAmount(buyGoldAmount);
            //买金人数  当天所有买金用户人数，如一个用户在一天内购买了两次则仅记录为1
            buyGoldBean.setBuyGoldNum(beanList.size());
            //买金克重
            buyGoldBean.setBuyGoldGram(buyGoldGram);
            //人均购买金额=当天交易总数/当天交易总数
            //当天交易总数
            //Integer dayTraderNum = beanList.stream().collect(Collectors.summingInt(BaseCountExtendBean::getTraderNum));
            buyGoldBean.setAverageBuyGoldAmount(buyGoldAmount.divide(new BigDecimal(buyGoldBean.getBuyGoldNum()), 2, BigDecimal.ROUND_HALF_UP));
            buyGoldList.add(buyGoldBean);
        }

        //根据渠道id获取当前渠道总uv  分日
        List<UvEntity> uvEntityList = channelMapper.queryUvBychannelId(channelId, 2);
        Map<String, List<UvEntity>> listMap = null;
        if (!org.springframework.util.CollectionUtils.isEmpty(uvEntityList)) {
            if (uvEntityList.size() == 1 && uvEntityList.get(0).getDay() == null) {
                listMap = new HashMap<>();
            } else {
                listMap = uvEntityList.stream().collect(Collectors.groupingBy(b -> b.getDay()));
            }

        }

        List<BaseOperationBean> list = channelMapper.statistics(channelId, 2);
        //按照类型进行分组 1,2,3,4,5  每种类型里面的日期是不会重复
        Map<Integer, List<BaseOperationBean>> typeMaplist = list.stream().collect(Collectors.groupingBy(BaseOperationBean::getType));
        List<BaseOperationBean> list1 = null;
        List<BaseOperationBean> list2 = null;
        List<BaseOperationBean> list3 = null;
        List<BaseOperationBean> list4 = null;
        List<BaseOperationBean> list5 = null;
        for (int i = 1; i <= 6; i++) {
            if (typeMaplist.get(i) != null) {
                switch (i) {
                    case 1:
                        list1 = typeMaplist.get(i);
                        break;
                    case 2:
                        list2 = typeMaplist.get(i);
                        break;
                    case 3:
                        list3 = typeMaplist.get(i);
                        break;

                    case 4:
                        list4 = typeMaplist.get(i);
                        break;

                    case 5:
                        list5 = typeMaplist.get(i);
                        break;
                }
            }
        }
        //设置开始时间
        LocalDate startTime = LocalDate.parse(channelStartTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse(channelEndTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //获取查询出的天数
        int day = Integer.valueOf(Common.until(startTime, endTime) + "") + 1;
        for (int i = 0; i < day; i++) {
            //当前日期时间字符串
            String startTimeString = startTime.toString();
            ChannelStatisticsBean entity = new ChannelStatisticsBean();
            entity.setDay(startTimeString);
            if (list != null && !list.isEmpty()) {
                if (!org.springframework.util.CollectionUtils.isEmpty(list1)) {
                    list1.stream().filter(o -> o.getDay().contains(startTimeString)).forEach(bean -> {
                        entity.setRegisterNum(bean.getRegisterNum());
                        entity.setBdCardNum(bean.getBdCardNum());
                    });
                }

                if (!org.springframework.util.CollectionUtils.isEmpty(list2)) {
                    list2.stream().filter(o -> o.getDay().contains(startTimeString)).forEach(bean -> {
                        entity.setSoldGoldNum(bean.getSoldGoldNum());
                        entity.setSoldGoldGram(bean.getSoldGoldGram());
                    });
                }
                if (!org.springframework.util.CollectionUtils.isEmpty(list3)) {
                    list3.stream().filter(o -> o.getDay().contains(startTimeString)).forEach(bean -> {
                        entity.setBalanceAmount(bean.getBalanceAmount());
                    });
                }

                if (!org.springframework.util.CollectionUtils.isEmpty(list4)) {
                    list4.stream().filter(o -> o.getDay().contains(startTimeString)).forEach(bean -> {
                        entity.setWithdrawAmount(bean.getWithdrawAmount());
                    });
                }
                if (!org.springframework.util.CollectionUtils.isEmpty(list5)) {
                    list5.stream().filter(o -> o.getDay().contains(startTimeString)).forEach(bean -> {
                        entity.setCouponNum(bean.getCouponNum());
                    });
                }
                List<BuyGoldBean> resultBuyGoldList = buyGoldList.stream().filter(o -> o.getDay().contains(startTimeString)).collect(Collectors.toList());
                if (resultBuyGoldList != null && !resultBuyGoldList.isEmpty()) {
                    BuyGoldBean buyGoldBean = resultBuyGoldList.get(0);
                    BeanUtils.copyProperties(buyGoldBean, entity);
                }

                if (!org.springframework.util.CollectionUtils.isEmpty(channelList)) {
                    channelList.stream().filter(o -> o.getKeywords().contains(startTimeString)).forEach(b->{
                        entity.setNewJoinUserNum(Integer.valueOf(b.getTotal().toString()));
                    });
                }
            }
            if (listMap != null && listMap.get(startTimeString) != null) {
                entity.setUv(listMap.get(startTimeString).get(0).getUv());
            }

            resultList.add(entity);
            startTime = startTime.plusDays(1);
        }

        //数据分页
        if (resultList != null && !resultList.isEmpty()) {
            Collections.reverse(resultList);  //倒序排列
            int total = resultList.size();
            //计算
            int num = (pageNum - 1) * pageSize;
            resultList = resultList.stream().skip(num).collect(Collectors.toList());
            List<BaseOperationBean> pageList = resultList.stream().limit(pageSize).collect(Collectors.toList());
            Map resultMap = new HashMap();
           // if (!flag) {
                Integer totalBuyGoldGram = resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getBuyGoldGram));
                Integer totalBuyGoldNum = resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getBuyGoldNum));
                BigDecimal totalTraderAmount = resultList.stream().map(ChannelStatisticsBean::getBuyGoldAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                Integer soldGoldNum = resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getSoldGoldNum));
                //注册总数（人）
                resultMap.put("totalRegisterNum", resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getRegisterNum)));
                //绑卡总数（人）
                resultMap.put("totalBdCardNum", resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getBdCardNum)));
                if (traderNumMap == null || traderNumMap.size() == 0) {
                    //首投人数
                    resultMap.put("totalFirstBuyNum", 0);
                } else {
                    //首投人数
                    resultMap.put("totalFirstBuyNum", traderNumMap.get(1) == null ? 0 : traderNumMap.get(1).stream().count());
                }

                //买金人数（人）  = 每日买金人数总和
                resultMap.put("totalBuyGoldNum", totalBuyGoldNum);
                //卖金人数
                resultMap.put("totalSoldGoldNum", soldGoldNum);
                //买金克重（g）
                resultMap.put("totalBuyGoldGram", totalBuyGoldGram);
                //买金金额（元）
                resultMap.put("totalTraderAmount", totalTraderAmount);
                //人均购买金额（元）= 交易总量/交易总数
                resultMap.put("totalAverageBuyAmount", totalTraderAmount.compareTo(new BigDecimal(0)) == 0 ? 0 : totalTraderAmount.divide(new BigDecimal(totalBuyGoldNum), 2, BigDecimal.ROUND_HALF_UP));
                //用户账户总余额（元）
                resultMap.put("totalBalanceAmount", resultList.stream().map(ChannelStatisticsBean::getBalanceAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                //红包使用人数（人）
                resultMap.put("totalCouponNum", resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getCouponNum)));
                //活动参与人数（人）
                resultMap.put("newJoinUserNum", resultList.stream().collect(Collectors.summingInt(ChannelStatisticsBean::getNewJoinUserNum)));
                return new DataOtherTable<>(pageNum, pageSize, total, pageList, resultMap);
            }
       // }
        return null;
    }

    /**
     * 获取邀请码
     **/
    private String getInviteCode() {//需要区别之前的邀请码规则
        String key = RedisConstantUtil.INVITE_CODE_KEY;
        Set<String> codes = redisTemplate.opsForSet().members(key);
        String inviteCode = "";
        if (codes == null || codes.size() == 0) {
            inviteCode = UF.getInviteCode();
            redisTemplate.opsForSet().add(key, inviteCode);
        } else {
            for (; ; ) {
                inviteCode = UF.getInviteCode();
                if (!codes.contains(inviteCode)) {
                    break;
                }
            }
            redisTemplate.opsForSet().add(key, inviteCode);
        }
        return inviteCode;
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5Hex("UG945723"));
    }
}
